/** 
* Global variables
*/
var babySlider = document.getElementById("babySlider");
var panelMask = document.getElementById("panelMask");
var swapPanel = document.getElementById("swapPanel");
var progressMeter = document.getElementById("progressMeter");
var parentSlider = document.getElementById("parentSlider");

var continueButton, offerButton, continueButtonValue, originalBtnValue;
var padToggleLoaded = false;

/**
* PAYPAL.Checkout.Review object
*/
PAYPAL.Checkout.Review = {

	hintHolder: "",
	
	init: function(){
		if(document.getElementById("loginfo")){
			YUE.onDOMReady("signoutcontent",YUD.addClass('signoutcontent','hide'));
                        YUE.addListener(document, "click", function(e){
                        var target = (e && e.target) || (event && event.srcElement);
                        var obj = document.getElementById('signoutcontent');

                        if(target.id=="log_content" || target.id=="email_id"){
                                if(obj.className =='opened')
                                   obj.className ='hide';
                                else
                                   obj.className ='opened';
                        }
                        else
                                obj.className ='hide';
                        });
                }
		// Set the initial values for the text of the continue button and the text to use for continue button if credit offer is selected
		offerButton = document.getElementById("creditOfferSbmtBtnLabel");
		continueButton = document.getElementById("continue");
		continueButtonValue = "";
		if (continueButton) {
			continueButtonValue = continueButton.value;
		}

		review.merchantConfigSection();
		YUE.addListener("subscribePromotionalEmails", "click", review.subscribePromotionalEmails);
		PAYPAL.Checkout.Shared.init();
		if (document.getElementById("mpi_offer_selected")) {
			review.creditSelection();
			YUE.addListener("offerImage", "click", function(){document.getElementById("mpi_offer_selected").checked = true; review.creditSelection();});
			YUE.addListener(["currentfunding", "mpi_offer_selected", "alterfunding"], "click", review.creditSelection);	
		}
		// PAD Enhancements
		if (document.getElementById("toggle_pad")) {
			originalBtnValue = continueButtonValue;
			YUE.addListener("toggle_pad", "click", function(){
				review.togglePayAfterDelivery();
			});
		}
		var padMsgNonJsHide = document.getElementById("padMsgNonJsHide");
                        if(padMsgNonJsHide){
                                padMsgNonJsHide.style.display="inline";
                        }		

		YUD.addClass("parentForm", "edit");
	
		//Change the panel mask message
		YUE.addListener("addDiscount", "click", function(){
			PAYPAL.Checkout.Slider.showPanelMsg("defaultMsg");
		});
		YUE.addListener("changeNoteButton", "click", function(){
			PAYPAL.Checkout.Slider.showPanelMsg("defaultMsg");
		});
		YUE.addListener("changeAddressButton", "click", function(){
			PAYPAL.Checkout.Slider.showPanelMsg("shippingMsg");
		});
		YUE.addListener("changePhoneButton", "click", function(){
			PAYPAL.Checkout.Slider.showPanelMsg("reviewMsg");
		});

		YUE.onDOMReady(function(){setTimeout(
			function(){
				if(document.getElementById("creditOfferTriggerButton")){
					var button = document.getElementById("creditOfferTriggerButton");
					PCU.newTarget = button;
					button.click();
					button.parentNode.removeChild(button);
				}
			}, 2500);}
		);
		
		//35133 StreamLine Phase 2 autosubmit in UX Flow
		YUE.onDOMReady(function(){setTimeout(
			function(){
				var button = document.getElementById("liftLimitTriggerButton");
				if (button) {
					PCU.newTarget = button;
					button.click();
					button.parentNode.removeChild(button);
				}
			}, 2000);}
		);

		// 51943 Replatforming - autosubmit to show edit shipping address.
		YUE.onAvailable("editShippingAddressTriggerButton", function(){
			var button = document.getElementById("editShippingAddressTriggerButton");
			PCU.newTarget = button;
			button.click();
			button.parentNode.removeChild(button);
		});
		
		// Move Pinless Debit Lightbox
		var iavinprogress = document.getElementById("pinlessDebitLB");
		if (iavinprogress) {
			var oForm = document.getElementById("parentForm"), hiddenElement = document.createElement("input"), hiddenSubmit = document.createElement("input");

			iavinprogress.parentNode.removeChild(iavinprogress);
			document.body.appendChild(iavinprogress);

			hiddenElement.setAttribute("type", "hidden");
			hiddenElement.setAttribute("name", "debit_network_switch");
			hiddenElement.setAttribute("id", "hidden_debit_network_switch");
			oForm.appendChild(hiddenElement);

			hiddenSubmit.setAttribute("type", "hidden");
			hiddenSubmit.setAttribute("name", "debit.network.switch.submit");
			hiddenSubmit.setAttribute("value", "Submit");
			oForm.appendChild(hiddenSubmit);
		}

		// Sync Pinless Debit form element
		YUE.addListener("debit.network.switch.submit", "click", function(e) {
			var pinlessDebitLB = document.getElementById("pinlessDebitLB"), parentForm = document.getElementById("parentForm");
			if (pinlessDebitLB) {
				var debitOptions = pinlessDebitLB.getElementsByTagName("input"), i, count = debitOptions.length, hiddenMaster = document.getElementById("hidden_debit_network_switch");
				for (i = 0; i < count; i++){
					if (debitOptions.item(i).checked && hiddenMaster) {
						hiddenMaster.value = debitOptions.item(i).value;
					}
				}
			}
			if (parentForm) {
				parentForm.submit();
			}
		});
		if (window.adbPageInit) {
			YUE.onContentReady("add_uach_bank", window.adbPageInit);
			PAYPAL.fmx.addBank.init();
		}
		if (window.iavPageInit) {
			YUE.onContentReady("verify.your.account", window.iavPageInit);
		}

		// Add listeners for payment method radios
		var n = document.getElementsByTagName("input"), l = n.length, c;
		for (c = 0; c < l; c++) {
			if (n.item(c).type == "radio") {
				YUE.addListener(n.item(c), "click", this.evtPaymentMethodChanged);
			}
		}
		// Call the configuration method to initialize the form
		this.evtPaymentMethodChanged();
		
		//Disable the language toggler buttons . 
		var langToggleContainer = document.getElementById("languageToggler");
		if(langToggleContainer){
			var btns = YUD.getElementsByClassName("disabledButton", "input", langToggleContainer);
			if(btns && btns.length>0){
				btns[0].setAttribute("disabled","disabled");
			}
			
		}
	},

	/**
	* Applies accessAid class to elements with "noScript" class.
	*/
	noScriptAid: function(){
		if (PAYPAL.Checkout && PAYPAL.Checkout.Util && PAYPAL.Checkout.Util.noScriptAid) {
			PAYPAL.Checkout.Util.noScriptAid(YUD.getElementsByClassName("noScript"), "on");
		}
	},
 
	/**
	* Disables the 'Pay Now' button only when 'disabled' is passed.
	* @param {string} flag Determines if the button is disabled (arg = 'disabled')
	*/
	disablePayButton: function(flag){
		if (continueButton) {
			continueButton.disabled = (flag) ? "disabled" : false;
			var PPSCR01437243 = document.getElementById("continue_abovefold");
			if (PPSCR01437243) {
				PPSCR01437243.disabled = continueButton.disabled;
			}
		}
	},

	/**
	* Attaches onClick event listeners to button links, with a callback
	* function to run reviewSlider. Requires two parameters.
	* @param {element} el Element reference for the event
	* @param {method} fn Method the event invokes
	*/
	buttonLinkEvent: function(el, fn, formId){
		formId = formId || "review";
		var btn = document.getElementById(el), eventObj = {callback:fn};
		YUE.addListener(btn, "click", function(e){
			YUE.preventDefault(e);
			review.reviewSlider(eventObj.callback, btn, formId);
		}, eventObj);
	},

	/**
	* Event handler for updating Seller Note counter and hint text
	* @param {obj} e Event object that invoked this method
	*/
	noteToSellersEvent: function(e){
		e = e || window.event;
		var el = this, charCounterId = "charsLeft" + el.id.replace(/^.+(_[0-9]+)$/, "$1");
		//We could use a switch statement and check all the event types, but the if is more efficient in this case
		if (e.type == "focus") {
			if (YUD.hasClass(el, "noteToInfo")){
				this.hintHolder = el.value;
				el.value = "";
				YUD.removeClass(el, "noteToInfo");
			}
			PAYPAL.Checkout.Util.charCounter(el, charCounterId, 255);
		} else if (e.type == "blur") {
			if (el.value == "" && this.hintHolder !== undefined){
				el.value = this.hintHolder;
				YUD.addClass(el, "noteToInfo");
			}
		} else {
			PAYPAL.Checkout.Util.charCounter(el, charCounterId, 255);
		}
	},

	/**
	* 
	*/
	noteToSellerEvent: function(e){
		var el = document.getElementById("noteToSeller");
		//We could use a switch statement and check all the event types, but the if is more efficient in this case
		if (e.type == "blur") {
			if (el.value == "" && this.hintHolder !== undefined) {
				el.value = this.hintHolder;
				YUD.addClass(el, "secondary");
			}
		} else if (e.type == "focus") {
			if (YUD.hasClass(el, "secondary")){
				this.hintHolder = el.value;
				el.value = "";
				YUD.removeClass(el, "secondary");
			}
		} else {
			PAYPAL.Checkout.Util.charCounter(el, "charsLeft", 255);
		}
	},
		
	/**
	* Handles functionality for the Edit Billing slider
	*/
	initEditBilling: function(){
		review.noScriptAid();
		YUE.onContentReady("paymentMethods", PAYPAL.Checkout.ChoosePaymentMethod.init, PAYPAL.Checkout.ChoosePaymentMethod, true);
		YUE.onContentReady("cc_number", PAYPAL.CreditCardInput.init, PAYPAL.CreditCardInput, true);
		YUE.onContentReady("usZip", function(){
			PAYPAL.widget.Address.init(this);
		});
		YUE.addListener("cancel", "click", review.closeReviewSlider);
	},
	
	/**
	* Handles functionality for the Incentive/Discount slider
	*/
	initChangeDiscount: function(){
		var addMore = new PAYPAL.widget.AddMore("additional-incentives");
		review.buttonLinkEvent("applyIncentiveSlider", review.initChangeDiscount, "editDiscountForm");
		YUE.addListener("cancelIncentiveSlider", "click", review.closeReviewSlider);
		//focus user on the first incentive checkbox if it exists
		if (document.getElementById("pie_code")) {
			document.getElementById("pie_code").focus();
		}
	},

	/**
	* Handles show/hide for payment methods
	*/
	evtPaymentMethodChanged: function(){
		var cbx = document.getElementById("bml_financing_offer_cbx");
		if (cbx) {
			YUD.addClass(cbx, "accessAid");
			var n = document.getElementsByTagName("input"), l = n.length, c;
			for (c = 0; c < l; c++) {
				if (n.item(c).type == "radio" && n.item(c).value == "BML" && n.item(c).checked) {
					YUD.removeClass(cbx, "accessAid");
					break;
				}
			}
		}
	},

	/**
	* 
	*/
	merchantConfigSection: function(){
		YUD.addClass("showEmailOnload", "show");
		YUD.addClass("showEmail", "hide");
	},

	/**
	* 
	*/
	subscribePromotionalEmails: function(){
		var emailSubscribed = document.getElementById("subscribePromotionalEmails");
		if (emailSubscribed) {
			YUD.removeClass("showEmailOnload", (emailSubscribed.checked ? "hide" : "show"));
			YUD.removeClass("showEmail", (emailSubscribed.checked ? "hide" : "show"));
			YUD.addClass("showEmailOnload", (emailSubscribed.checked ? "show" : "hide"));
			YUD.addClass("showEmail", (emailSubscribed.checked ? "show" : "hide"));
		}
	},

	/**
	* 
	*/
	creditSelection: function(){
		var funding = document.getElementById("currentfunding"), alterFunding = document.getElementById("alterfunding"), mpi = document.getElementById("mpi_offer_selected"), padToggle	= document.getElementById("toggle_pad");
				
		if ((this.id == "currentfunding" || funding.checked) || (this.id == "alterfunding")) {
			if (offerButton) {
				if (continueButton) {					
					continueButton.value = continueButtonValue;					
					var PPSCR01437243 = document.getElementById("continue_abovefold");
					if (PPSCR01437243) {
						PPSCR01437243.value = continueButton.value;
					}
					if (padToggle) {
						review.trackPAD(false);
						if (padToggle.checked == true){
							review.trackPAD(true);
							YUD.replaceClass("padTerms", "hide", "show");
							YUD.replaceClass("PADAgreement", "hide", "show");
							if(padToggleLoaded) {								
								continueButton.value = document.getElementById("padSbmtBtnLabel").value;		
							}	
						}
					}
				}
				YUD.replaceClass("coConfirm", "show", "hide");
				YUD.replaceClass("sbmtBtnHelpText", "hide", "show");
			}
			YUD.replaceClass("defaultFunding", "show", "hide");
			YUD.replaceClass("creditOfferAcceptance", "show", "hide");
			YUD.replaceClass("fundingMixSection", "notselected", "selected");
			YUD.replaceClass("creditOfferSection", "selected", "notselected");
			
			// for 50833-uACH-AU: re-setting the parent-form
			if((YUD.hasClass(continueButton, 'babyOpen') && mpi) && ((mpi.value=='UNVERIFIED_BANK' && YUD.get('bankNotRflag')) || mpi.value=='DEBIT_CARD')){
				// if the current selection is not uACH-NotR offer, toggle the button for parent-submit
				review.toggleButtonForSlider(['babyOpen','parentSubmit']);
			}
		} else if (this.id == "mpi_offer_selected" || mpi.checked) {
			
			if (offerButton){
				if (continueButton) {
					continueButton.value = offerButton.value;
					var PPSCR01437243 = document.getElementById("continue_abovefold");
					if (PPSCR01437243) {
						PPSCR01437243.value = continueButton.value;
					}
				}
				YUD.replaceClass("coConfirm", "hide", "show");
				YUD.replaceClass("sbmtBtnHelpText", "show", "hide");
			}
			YUD.replaceClass("defaultFunding", "hide", "show");
			YUD.replaceClass("creditOfferAcceptance", "hide", "show");
			YUD.replaceClass("fundingMixSection", "selected", "notselected");
			YUD.replaceClass("creditOfferSection", "notselected", "selected");
			if(padToggle){
				YUD.replaceClass("PADAgreement", "show", "hide");
				YUD.replaceClass("padTerms", "show", "hide");
				review.trackPAD(false);
            }
			// for 50833-uACH-AU: to open add-bank form in baby-slider
			if(mpi.checked && ((mpi.value=='UNVERIFIED_BANK' && YUD.get('bankNotRflag')) || mpi.value=='DEBIT_CARD')){
				// if the current selection is NotR offer, toggle the button to open baby-slider
				review.toggleButtonForSlider(['parentSubmit','babyOpen']);
			}
		}
		PCU.resizeMiniCart(true);
	},
	
	/**
	* Manipulates the pay-now/continue buttons in the RYI page to open a baby-slider
	* onclicked; also toggles to restore to their default behavior as well.
	* @param [className1, className2] array className1 to remove from the two paynow/continue buttons
	*										className2 to append to the two paynow/continue buttons
	*		 ['parentSubmit','babyOpen'] || ['babyOpen','parentSubmit']
	*/	
	toggleButtonForSlider: function(classNames){
		if(continueButton && typeof(classNames)=='object' && classNames.length==2){
			// init with the bottom-continue button
			var buttonAray = [continueButton];
			// is top-button present, if so save it
			var topContinueButton = YUD.get('continue_abovefold');
			if(topContinueButton) buttonAray[1] = topContinueButton;
			// remove-n-add the requested class-selectors for the button(s)
			YUD.replaceClass(buttonAray, classNames[0], classNames[1]);
		}
	},
	/**
	* Click Tracking When Checkbox checked and PAD button pressed
	*/
	trackPAD: function(enable){
		var continueAboveFold = document.getElementById("continue_abovefold"),
			trackValue	  = document.getElementById("padTrack").value;
		
		if(enable){
			if(!YUD.hasClass(continueButton, trackValue)){
				YUD.addClass(continueButton, trackValue);			
				if (continueAboveFold) {
					YUD.addClass(continueAboveFold, trackValue);
				}
			}
		} else {
			if(YUD.hasClass(continueButton, trackValue)){
				YUD.removeClass(continueButton, trackValue);			
				if (continueAboveFold) {
					YUD.removeClass(continueAboveFold, trackValue);
				}
			}
		}
	},
	/**
	* toggling the payment-method, buttons for iACH/PAD
	*/
	togglePayAfterDelivery: function(){
		var padToggle			= document.getElementById("toggle_pad"), 
			padFundingDefault	= document.getElementById("padFundingDefault"),
			padBtnValue			= document.getElementById("padSbmtBtnLabel").value,
			padAlternateFunding	= YUD.getElementsByClassName("padAlternateFunding"),
			padDefaultFunding	= YUD.getElementsByClassName("padDefaultFunding"),
			padExchange			= YUD.getElementsByClassName("padExchange"),
			secondFunding		= document.getElementById("alterfunding"),
			firstFunding		= document.getElementById("currentfunding"),
			paymentSectionFocus = document.getElementById("funding_select");
			
			padToggleLoaded		= true; 
			if(padToggle.checked == true){	
				review.trackPAD(true);	
				if(padFundingDefault.value == "iach") {
					YUD.replaceClass(padAlternateFunding, "hide", "show");
					YUD.replaceClass("padAlternateBufs", "hide", "show");
					YUD.addClass(padDefaultFunding, "hide");					
					if(firstFunding && secondFunding){
						firstFunding.checked = false;
						secondFunding.checked = true;
					}								
					YUD.addClass("padDefaultBufs", "hide");
				} else {
					YUD.removeClass(padDefaultFunding, "hide");
					YUD.removeClass("padDefaultBufs", "hide");
					YUD.replaceClass(padAlternateFunding, "show", "hide");
					YUD.replaceClass("padAlternateBufs", "show", "hide");
					
					if(firstFunding && secondFunding){
						secondFunding.checked = false;
						firstFunding.checked = true;
					}										
					padBtnValue=originalBtnValue;
				}
				YUD.replaceClass("padTerms", "hide", "show");
				YUD.replaceClass("padBenefit", "hide", "show");	
				YUD.replaceClass(padExchange, "hide", "show");
				YUD.replaceClass("iach_message", "show", "hide");
				YUD.replaceClass("pad_message", "hide", "show");
				YUD.replaceClass("exchange-rate", "show", "hide");
				if(paymentSectionFocus){
					YUD.setAttribute(paymentSectionFocus,'tabIndex','0');
					paymentSectionFocus.focus();
				}
				if(document.getElementById("pad-promo")) {
					YUD.replaceClass("pad-promo","show","hide");
					YUD.removeClass("pad_checkbox","pad-corner");
				}
				
			} else {
				review.trackPAD(false);
				if(padFundingDefault.value == "iach") {
					YUD.removeClass(padDefaultFunding, "hide");
					YUD.removeClass("padDefaultBufs", "hide");
					YUD.replaceClass(padAlternateFunding, "show", "hide");
					YUD.replaceClass("padAlternateBufs", "show", "hide");
					
					if(firstFunding && secondFunding){
						secondFunding.checked = false;
						firstFunding.checked = true;
					}					
					padBtnValue=originalBtnValue;
				} else {
					YUD.replaceClass(padAlternateFunding, "hide", "show");
					YUD.replaceClass("padAlternateBufs", "hide", "show");
					YUD.addClass(padDefaultFunding, "hide");
					
					if(firstFunding && secondFunding){
						firstFunding.checked = false;
						secondFunding.checked = true;
					}
					
					YUD.addClass("padDefaultBufs", "hide");
				}
				YUD.replaceClass("padTerms", "show", "hide");
				YUD.replaceClass("padBenefit", "show", "hide");
				YUD.replaceClass(padExchange, "show", "hide");
				YUD.replaceClass("iach_message", "hide", "show");
				YUD.replaceClass("pad_message", "show", "hide");
				YUD.replaceClass("exchange-rate", "hide", "show");
				if(paymentSectionFocus){
					YUD.setAttribute(paymentSectionFocus,'tabIndex','0');
					paymentSectionFocus.focus();
				}
				if(document.getElementById("pad-promo")) {
					YUD.replaceClass("pad-promo","hide","show");
					YUD.addClass("pad_checkbox","pad-corner");
				}
									
			}
			
			if (continueButton) {
				continueButton.value = padBtnValue;
				var PPSCR01437243 = document.getElementById("continue_abovefold");
				if (PPSCR01437243) {
					PPSCR01437243.value = continueButton.value;
				}
			}
			if (document.getElementById("mpi_offer_selected")) {
				YUD.replaceClass("fundingMixSection", "notselected", "selected");
				YUD.replaceClass("creditOfferSection", "selected", "notselected");
				YUD.addClass("funding-mix", "middle");	
				YUD.replaceClass("coConfirm", "show", "hide");
				YUD.replaceClass("sbmtBtnHelpText", "hide", "show");
			}
		
		PCU.resizeMiniCart(true);
	}
};
var review = PAYPAL.Checkout.Review;
PAYPAL.Checkout.Review.init();

// IXO/Turbo FSO code
IXO.writeEil = function() {
	if ( IXO.eilCheckCount === false ) { IXO.eilCheckCount = 0; }
	IXO.eilCheckCount++;
	if ( IXO.eilCheckCount >= IXO.maxEilChecks ) { // FAIL
		IXO.eilCheckCount = false;
		return false;
	}
	
	if ( IXO.eilCheckCount % 5 === 0 ) {
		IXO.reIncludeFso();
	}
	
	var fso = IXO.getFsoRef();
	if ( fso !== false && PAYPAL.tns.ermList ) {
		IXO.eilCheckCount = false;
		fso.writeErmListValue(PAYPAL.tns.ermList);
		return true;
	}
	else {
		setTimeout(IXO.writeEil, IXO.eilCheckInterval);
	}
};
if(PAYPAL.tns && PAYPAL.tns.ermList){
IXO.writeEil();
}
